const Base = require('./base.js');
const querystring = require('querystring');
const path = require('path');
const fs = require('fs');
const mustache = require('mustache');
const request = require('request');
const { appid, appSecret, webAuthTokenUrl } = require('../weChat');

// 获取授权时微信端返回的code
const getCode = ctx => {
  const { code } = ctx.query;
  if (!code) throw new Error('初次授权绝对需要code');
  return code;
};

// 获取access_tocken 与 id
const getTokenAndId = code => {
  return new Promise((resolve, reject) => {
    const url = webAuthTokenUrl;

    const queryStr = querystring.stringify({
      appid: appid,
      secret: appSecret,
      code: code,
      grant_type: 'authorization_code'
    });

    request({ url: url + queryStr }, (error, response, body) => {
      if (error) {
        reject(response && response.statusCode + ': ' + error);
      } else {
        const { openid, access_token } = JSON.parse(body);
        if (openid) {
          resolve({ openid, access_token });
        } else {
          reject(new Error('无法根据code来获取有效的openid'));
        }
      }
    });
  });
};

// 根据模版与openid 生成一个 html 文档返回给客户端
const getHtml = info => {
  const page = fs.readFileSync(path.join(__dirname, '../../static/template.html'), 'utf8');
  return mustache.to_html(page, { info });
};

const getUserInfo = ({ access_token, openid }) => {
  return new Promise((resolve, reject) => {
    // 有了token 再去获取用户的数
    request({
      url: 'https://api.weixin.qq.com/sns/userinfo?' +
      'access_token=' + access_token +
      '&openid=' + openid +
      '&lang=zh_CN'
    }, (error, response, body) => {
      if (error) {
        reject(new Error(response && response.statusCode + ': ' + error));
      } else {
        const result = JSON.parse(body);
        const {errcode, errmsg} = result;
        if (errcode) {
          reject(new Error('获取用户数据发生了错误 ' + errmsg));
        } else {
          resolve(result);
        }
      }
    });
  });
};

module.exports = class extends Base {
  async indexAction() {
    think.logger.info('来来');
    // 根据模版来生成index.html 文件
    const code = getCode(this.ctx);
    const tokenAndId = await getTokenAndId(code);

    // 获取用户数据
    const info = await getUserInfo(tokenAndId);
    // 响应 html
    this.body = getHtml(JSON.stringify(info));
  }
};
